package Signal

import (
	"sync"
	"time"
)

// Lock 信号锁：作用是模拟JAVA的Wait(timeout)、Notify()
type Lock struct {
	mutex sync.Mutex
	cond  *sync.Cond
	wait  int64
}

func New(timeout int64) *Lock {
	signal := &Lock{}
	signal.cond = sync.NewCond(&signal.mutex)
	signal.wait = timeout

	if signal.wait < 1000 {
		signal.wait = 1000
	}

	go func() {
		for true {
			time.Sleep(time.Duration(signal.wait) * time.Millisecond)
			signal.Signal()
		}
	}()

	return signal
}

func (e *Lock) Wait() {
	e.cond.L.Lock()
	e.cond.Wait()
	e.cond.L.Unlock()
}

func (e *Lock) Signal() {
	e.cond.L.Lock()
	e.cond.Signal()
	e.cond.L.Unlock()
}
